// contexts/AuthContext.js - 认证上下文
import React, { createContext, useContext, useState, useEffect } from 'react';
import api from '../services/api';
import { logInfo, logError } from '../logger';

// 创建认证上下文
const AuthContext = createContext();

/**
 * 认证提供者组件
 * @param {Object} children - 子组件
 */
export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  // 初始化时检查用户是否已登录
  useEffect(() => {
    const initializeAuth = async () => {
      const token = localStorage.getItem('token');
      if (token) {
        try {
          // 验证token有效性
          const userData = await api.getCurrentUser();
          setUser(userData.data);
          setIsAuthenticated(true);
          logInfo('用户已登录', { userId: userData.data.id });
        } catch (error) {
          logError('token验证失败', { error: error.message });
          // token无效，清除本地存储
          localStorage.removeItem('token');
        }
      }
      setLoading(false);
    };

    initializeAuth();
  }, []);

  /**
   * 用户登录
   * @param {Object} credentials - 登录凭据
   * @returns {Promise} 登录结果Promise
   */
  const login = async (credentials) => {
    try {
      const data = await api.login(credentials);
      setUser(data.data);
      setIsAuthenticated(true);
      logInfo('用户登录成功', { userId: data.data.id });
      return data;
    } catch (error) {
      logError('用户登录失败', { error: error.message });
      throw error;
    }
  };

  /**
   * 用户注册
   * @param {Object} userData - 用户数据
   * @returns {Promise} 注册结果Promise
   */
  const register = async (userData) => {
    try {
      const data = await api.register(userData);
      setUser(data.data);
      setIsAuthenticated(true);
      logInfo('用户注册成功', { userId: data.data.id });
      return data;
    } catch (error) {
      logError('用户注册失败', { error: error.message });
      throw error;
    }
  };

  /**
   * 用户登出
   */
  const logout = () => {
    setUser(null);
    setIsAuthenticated(false);
    localStorage.removeItem('token');
    logInfo('用户已登出');
  };

  /**
   * 更新用户资料
   * @param {Object} profileData - 用户资料数据
   * @returns {Promise} 更新结果Promise
   */
  const updateProfile = async (profileData) => {
    try {
      const data = await api.updateProfile(profileData);
      setUser(data.data);
      logInfo('用户资料更新成功', { userId: data.data.id });
      return data;
    } catch (error) {
      logError('用户资料更新失败', { error: error.message });
      throw error;
    }
  };

  // 认证上下文值
  const value = {
    user,
    isAuthenticated,
    loading,
    login,
    register,
    logout,
    updateProfile,
  };

  return (
    <AuthContext.Provider value={value}>
      {!loading && children}
    </AuthContext.Provider>
  );
};

/**
 * 使用认证上下文的钩子
 * @returns {Object} 认证上下文值
 */
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export default AuthContext;